package Server;

import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;

import mysqlCnnection.LogInCheck;
import ocsf.server.AbstractServer;
import ocsf.server.ConnectionToClient;

public class CCRM_Server_Controller extends AbstractServer{
	
	private Vector<Object[]> clientsVec =new Vector<Object[]>();
	
	public CCRM_Server_Controller(int port){
		super(port);
	}

	  /**
	   * This method handles any messages received from the client.
	   *
	   * @param msg The message received from the client.
	   * @param client The connection from which the message originated.
	   */
	  public synchronized void handleMessageFromClient(Object msg, ConnectionToClient client){
		  String[] str = null;
		  str = (String[])msg;
		  if (str[0].equals("Login")){
			  if (isAlreadyLogIn(str[1] , str[2], client))
				  return;
			  if (ifToAddToclientsVec(str[1] , str[2], client))
				  aAddToclientsVec(str[1] , str[2], client);
			  
			  return;
		  }
		  else
			  if (str[0].equals("LogOut")){
				  System.out.println(str[0]);
				  LogOut(client);
				  return;
			  }
		  try{
		    	ConnectionToUser connectionToUser = new ConnectionToUser((String[])msg);
		    	client.sendToClient(connectionToUser.sendMessageToClient());		    	
		    }
		  catch(IOException ioxception){
		    	System.out.println("ERROR to send message : " + msg + " to " + client);
		  }
		  catch(Exception e){
		    	System.out.println("ERROR!!!");
		  }    
	 }  
	  
	  /**
	   * 
	   */
	  private synchronized boolean isAlreadyLogIn(String username, String password, ConnectionToClient client){
		  int size = clientsVec.size();
		  boolean loginflasg = false;
		  int clienttoclose = -1;
		  Object[] clientinfo = null;
		  int i=0;
		  Thread[] clientThreadList = getClientConnections();
		  for (i=0; i < size; i++){
			  clientinfo = clientsVec.get(i);
			  if (clientinfo[0].equals(password) || clientinfo[1].equals(username)){
				  for (int j=0; j < clientThreadList.length; j++){
					  try{
						  if (((ConnectionToClient)clientThreadList[j]).getId() == (Long)clientinfo[3]){
							  if (((ConnectionToClient)clientThreadList[j]).isAlive()){
								  loginflasg = true;
							  }
							  else
								  clienttoclose = j;			    			
							  break;
						  }				    		
					  }
					  catch (Exception ex) {
						  clienttoclose = j;
						  break;
					  }
				  }
				  break;					    
			  }
		  }
		  if (loginflasg){
			  try{
				  client.sendToClient("AlreadyIN");	
				  return true;
			  }
			  catch(IOException ioxception){
				  return true;
			  }
		  }
		  else
			  if (i < size) 
				  clientsVec.removeElementAt(i);
		  if (clienttoclose > -1){
			  try {
				  ((ConnectionToClient)clientThreadList[clienttoclose]).close();
			  } 
			  catch (IOException e) {
			  }			 
		  }
		  return false;
	  }
	  
	  /**
	   * 
	   * @param username
	   * @param password
	   * @param client
	   * @return
	   */
	  private synchronized boolean ifToAddToclientsVec(String username, String password, ConnectionToClient client){
		  String strmsg=null;
		  try{
			  LogInCheck logincheck = new LogInCheck();
			  strmsg = logincheck.passwordAndUserNameCheck(username, password);
		  }
		  catch (Exception except){
				   	
		  }
			
		  try{
			  client.sendToClient(strmsg);
			  if (strmsg != null && !strmsg.equals("Ilegalusername")){
				  return true;					
			  }
			  return false;
		  }
		  catch (Exception e) {
			  return false;
		  }		  
	  } 
	  
	  /**
	   * 
	   * @param username
	   * @param password
	   * @param client
	   */
	  private synchronized void aAddToclientsVec(String username, String password, ConnectionToClient client){
		  Object[] clientinfo = new Object[4];
		  clientinfo[0] = password;
		  clientinfo[1] = username;
		  clientinfo[2] = client.getInetAddress();
		  clientinfo[3] = client.getId();
		  clientsVec.add(clientinfo);	                                  
	  }
	  
	  /**
	   * This method logOf the client from the system
	   * @param username
	   * @param password
	   * @param client
	   */
	  private synchronized void LogOut( ConnectionToClient client){
		  Object[] clientinfo = new Object[4];
		  for (Iterator<Object[]> it = clientsVec.iterator(); it.hasNext();){
			  clientinfo = (Object[])it.next();
			  if (clientinfo[3].equals(client.getId())){
				  it.remove();
				  try{
					  client.sendToClient("LoggedOut");
					  client.close();						
				  }
				  catch (IOException e) {					
				  }
				  return;
			  }				
		  }		  
	  }
	  

	    
	  public void clientConnected(ConnectionToClient client){
		  Thread[] clientThreadList = getClientConnections();

		  for (int i=0; i<clientThreadList.length; i++){
			  try{
				  System.out.println(((ConnectionToClient)clientThreadList[i]).getInetAddress());
				  System.out.println(((ConnectionToClient)clientThreadList[i]).getId());		    	 
			  }
			  catch (Exception ex) {   	 
		      }
		  }
		  System.out.println("********************");
		    
		  Object[] clientinfo = new Object[4];
		  for (Iterator<Object[]> it = clientsVec.iterator(); it.hasNext();){
			  clientinfo = (Object[])it.next();
			  System.out.println(clientinfo[0].toString()+clientinfo[1].toString()+clientinfo[2].toString()+clientinfo[3].toString());				
		  }
		  System.out.println("######################");    
	  }
	  
	  public synchronized void clientDisconnected(ConnectionToClient client) {
		  System.out.println("clientDisconnected:"+" ID: "+client.getId()+" Name: "+client.getName()); 
	  } 
	  
	  /**
	   * This method overrides the one in the superclass.  Called
	   * when the server starts listening for connections.
	   */
	  protected void serverStarted(){
	    System.out.println("Server listening for connections on port " + getPort());
	  }
	  
	  /**
	   * This method overrides the one in the superclass.  Called
	   * when the server stops listening for connections.
	   */
	  protected void serverStopped(){
	    System.out.println
	      ("Server has stopped listening for connections.");
	  }
}
